export default {
	data() {
		return {
			phoneLoad: false,
			rollingList: [],
			seckillTime: ['00', ':', '00', ':', '00'],
			seckillPro: {},
			newList: [],
			hotList: [],
			notice: {}
		}
	},
	async onLoad(options) {
		console.log("home index onLoad");
		// await self.onPageInit();
		// if (!this.$store.state.login.mobile) {
		// 	this.$refs.loginRef.popupOpen();
		// }
	},
	onShow() {
		const self = this;
		setTimeout(async () => {
			if (self.$store.state.login.token) {
				await self.onPageInit();
			} else {
				await self.onLogin();
			}
			self.nowTimeInterval = setInterval(() => {
				self.getSeckillTime();
			}, 1000)
		});
	},
	onHide() {
		clearInterval(this.nowTimeInterval);
	},
	async onPullDownRefresh() {
		if (this.$store.state.login.token) {
			await this.onPageInit();
		} else {
			await this.onLogin();
		}
		uni.stopPullDownRefresh();
	},
	methods: {
		// 登录
		async onLogin() {
			this.$store.commit('showLoading');
			const uniRes = await new Promise((resolve, reject) => {
				uni.login({
					provider: 'weixin',
					success: (res) => {
						resolve(res)
					},
					fail: (err) => {
						reject(err)
					},
				});
			});
			console.log("uniRes: ", uniRes);
			if (uniRes && uniRes.code) {
				// 调用云函数		
				const loginRes = await this.$uniCloudCallFunction({
					name: 'xxf-wechat',
					action: "wxLogin",
					data: {
						code: uniRes.code
					}
				});
				console.log("loginRes: ", loginRes);
				//判断是否返回了用户数据
				if (loginRes && loginRes._id) {
					this.$store.commit("login/setLoginInfo", {
						...loginRes,
						uid: loginRes._id,
					});
				}
			} else {
				this.$utils.showToast(this, {
					message: 'uni.login失败',
					mode: 2
				});
			}
			setTimeout(() => {
				this.$store.commit('hideLoading');
				if (this.$store.state.login.mobile) {
					uni.reLaunch({
						url: "/pages/home/index/index"
					});
				} else {
					this.$refs.loginRef.popupOpen();
				}
			}, 1500);
		},
		// 初始化页面数据
		async onPageInit() {
			if (this.phoneLoad) return;
			await this.getBanner();
			await this.getNewPro();
			await this.getHotPro();
			await this.getNotice();
		},
		// 获取banner
		async getBanner() {
			const bannerRes = await this.$uniCloudCallFunction({
				name: 'xxf-banner',
				action: "getBanner",
				data: {
					uid: this.$store.state.login.uid
				}
			});
			console.log("bannerRes: ", bannerRes);
			if (bannerRes) {
				this.rollingList = bannerRes.list || [];
			}
		},
		// 获取产品列表
		async getNewPro() {
			const productsRes = await this.$uniCloudCallFunction({
				name: 'xxf-product',
				action: "getNewList",
				data: {
					uid: this.$store.state.login.uid,
				}
			});
			console.log(`getNewPro productsRes: `, productsRes);
			if (productsRes) {
				this.newList = productsRes.list || [];
				this.seckillPro = productsRes.list[0];
			}
		},
		async getHotPro(type) {
			const productsRes = await this.$uniCloudCallFunction({
				name: 'xxf-product',
				action: "getHotList",
				data: {
					uid: this.$store.state.login.uid,
				}
			});
			console.log(`getHotPro productsRes: `, productsRes);
			if (productsRes) {
				this.hotList = productsRes.list || [];
			}
		},
		// 获取公告
		async getNotice() {
			const noticeRes = await this.$uniCloudCallFunction({
				name: 'xxf-message',
				action: "getNotice",
				data: {
					uid: this.$store.state.login.uid,
				}
			});
			console.log("noticeRes: ", noticeRes);
			if (noticeRes) {
				this.notice = noticeRes.list[0] || {};
			}
		},
		getSeckillTime() {
			const now = new Date();
			const endOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59); // 当天结束的时间
			const diff = endOfDay - now; // 计算剩余时间
			if (diff > 0) {
				// 计算时间
				const seconds = Math.floor(diff / 1000);
				const minutes = Math.floor(seconds / 60);
				const hours = Math.floor(minutes / 60);
				const days = Math.floor(hours / 24);

				let ss = seconds % 60;
				ss = ss <= 9 ? `0${ss}` : `${ss}`;
				let mm = minutes % 60;
				mm = mm <= 9 ? `0${mm}` : `${mm}`;
				let hh = hours % 60;
				hh = hh <= 9 ? `0${hh}` : `${hh}`;

				this.seckillTime = [hh, ':', mm, ':', ss];
			} else {
				// 如果时间已经过了当天的23:59:59，则显示0秒
				this.seckillTime = ['00', ':', '00', ':', '00'];
			}
		},
		accessQuick(e) {
			console.log('accessQuick', e);
			if (e.page_path) {
				uni.navigateTo({
					url: `${e.page_path}`,
				})
			}
		},
		searchFocus() {
			uni.navigateTo({
				url: `/pages/homePack/searchList/index`,
			})
		},
		toNewList() {
			uni.navigateTo({
				url: `/pages/homePack/newList/index`,
			})
		},
		toHotList() {
			uni.navigateTo({
				url: `/pages/homePack/hotList/index`,
			})
		},
		toSeckillList() {
			uni.navigateTo({
				url: `/pages/homePack/seckillList/index`,
			})
		},
		toDetail(e) {
			uni.navigateTo({
				url: `/pages/homePack/proDetail/index?id=${e._id}`,
			})
		},
		async openSpuPop(e) {
			console.log("openSpuPop: ", e);
			this.$refs.spuRef.popupOpen({
				type: "add",
				productInfo: e
			});
		},
		spuPopupChange(e) {
			if (e.show) {
				this.$store.commit('hideTabbar');
			} else {
				this.$store.commit('showTabbar');
			}
		},
		async toCart(e) {
			const addRes = await this.$uniCloudCallFunction({
				name: 'xxf-cart',
				action: "addToCart",
				data: {
					uid: this.$store.state.login.uid,
					product_info: e.product_info,
					spu_info: e.spu_info,
					count: e.count,
					status: '1'
				}
			});
			console.log("addRes: ", addRes);
			await this.$utils.showToast(this, {
				message: '已经加入购物车！',
				mode: 1
			});
		},
		toBooking(e) {
			const proList = [{
				cartId: '',
				productId: e.productId,
				spuId: e.spuId,
				count: e.count,
			}];
			uni.navigateTo({
				url: `/pages/homePack/booking/index?proList=${JSON.stringify(proList)}`
			});
		},
		loginChange(e) {
			if (e.show) {
				this.phoneLoad = true;
			} else {
				this.phoneLoad = false;
			}
		},
		async loginConfirm() {
			this.phoneLoad = false;
			uni.reLaunch({
				url: "/pages/home/index/index"
			})
		},
		async readNotice(id) {
			const readRes = await this.$uniCloudCallFunction({
				name: 'xxf-message',
				action: "readNotice",
				data: {
					uid: this.$store.state.login.uid,
					id: id
				}
			});
			console.log("readRes: ", readRes);

			uni.navigateTo({
				url: `/pages/minePack/messages/index`
			});
		},
		fabClick() {
			uni.showToast({
				title: '点击了悬浮按钮',
				icon: 'none'
			})
		},
		trigger(e) {
			console.log(e)
			this.content[e.index].active = !e.item.active
			uni.showModal({
				title: '提示',
				content: `您${this.content[e.index].active ? '选中了' : '取消了'}${e.item.text}`,
				success: function(res) {
					if (res.confirm) {
						console.log('用户点击确定')
					} else if (res.cancel) {
						console.log('用户点击取消')
					}
				}
			})
		},
	},
}